<template>
  <div class="app-container">
    <!-- 顶部搜索区域 -->
    <div class="filter-container">
      <el-row :gutter="10" type="flex" align="middle">
        <el-col :span="6">
          <el-input
            v-model="listQuery.name"
            placeholder="输入职员名称"
            clearable
            style="width: 100%"
          />
        </el-col>

        <el-col :span="12">
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <!-- <el-checkbox
            style="margin-left: 30px"
            v-model="listQuery.type"
            label="displayUse"
            >显示禁用职员</el-checkbox
          >
          <el-checkbox v-model="listQuery.type" label="positionManage"
            >职员管理</el-checkbox
          > -->
        </el-col>

        <el-col :span="6" style="text-align: right">
          <!-- <el-button type="success" @click="handleAdd" icon="el-icon-plus" disabled>新增</el-button> -->
          <!-- <el-button @click="handleImport">导入</el-button>
          <el-button @click="handleExport">导出</el-button>
          <el-button @click="handleRefresh">刷新</el-button> -->
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="staffList"
      element-loading-text="加载中"
      border
      fit
      highlight-current-row
      header-cell-style="background-color: #f5f7fa; color: #333;"
    >
      <el-table-column label="职员名称" prop="name" align="center" width="300" />
      <el-table-column label="手机号码" prop="mobile" align="center" />
      <el-table-column align="center" prop="loginName" label="登录名" />
      <el-table-column align="center" prop="parentName" label="部门" />
      <el-table-column align="center" prop="sex" label="性别" />
      <!-- <el-table-column label="状态" align="center" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column> -->

      <!-- <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)" disabled>
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)" disabled>
            删除
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页区域 -->

    <el-row :gutter="10" style="margin-top: 20px" type="flex" justify="end">
      <el-pagination
        background
        :current-page.sync="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>

    <!-- 新增/编辑职员对话框 -->
    <el-dialog
      :title="form.id ? '编辑' : '新增'"
      :visible.sync="dialogFormVisible"
      width="500px"
    >
      <el-form ref="staffForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="登录名" prop="loginName">
          <el-input
            v-model="form.loginName"
            placeholder="请输入登录名"
          />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="部门" prop="parent">
          <el-select v-model="form.parent" placeholder="请选择部门" style="width: 100%">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="form.sex"
            placeholder="请选择性别"
            style="width: 100%"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selStaffListApi,
  addUserApi,
  updateUserByIdApi,
  deleteUserByIdApi,
  selDepartmentListApi
} from '@/api/system'
export default {
  name: 'StaffManagement',
  data() {
    return {
      listLoading: false,
      dialogFormVisible: false,
      list: [
        {
          id: 1,
          code: 'D0001',
          name: '老板',
          mobile: '183****0000',
          enabled: true
        },
        {
          id: 2,
          code: 'D0002',
          name: '财务-玲',
          mobile: '159****1111',
          enabled: true
        },
        {
          id: 3,
          code: 'D0003',
          name: '采购-小陈',
          mobile: '',
          enabled: true
        },
        {
          id: 4,
          code: 'D0004',
          name: '采购-小王',
          mobile: '',
          enabled: true
        },
        {
          id: 5,
          code: 'D0005',
          name: '销售-小李',
          mobile: '',
          enabled: true
        },
        {
          id: 6,
          code: 'D0006',
          name: '销售-小东',
          mobile: '',
          enabled: true
        },
        {
          id: 7,
          code: 'D0007',
          name: '旗舰店店员',
          mobile: '',
          enabled: true
        },
        {
          id: 8,
          code: 'D0008',
          name: '2店店员',
          mobile: '',
          enabled: true
        },
        {
          id: 9,
          code: 'D0009',
          name: '1号仓库管理',
          mobile: '',
          enabled: true
        }
      ],
      total: 0,
      // 查询参数
      listQuery: {
        page: 1,
        pageSize: 10,
        name: '',
        mobile: '',
        parent: ''
      },
      staffList: [], // 职员列表
      // 新增/编辑职员表单
      form: {
        loginName: '', // 登录名
        name: '', // 姓名
        mobile: '', // 手机号
        password: '', // 密码
        parent: '', // 部门
        sex: '' // 性别
      },
      rules: {
        loginName: [
          { required: true, message: '请输入登录名', trigger: 'blur' }
        ],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        parent: [{ required: true, message: '请输入部门', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }]
      },
      tempStaff: {
        id: null,
        code: '',
        name: '',
        mobile: '',
        enabled: true
      },
      // 部门列表查询
      departmentListQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      departmentList: [] // 部门列表
    }
  },
  created() {
    // this.getList();
    // this.getDepartmentList();
    this.getStaffList()
    this.getDepartmentList()
  },
  methods: {
    getList() {
      this.listLoading = true
      // 在实际应用中，这里会调用API获取职员列表
      // 模拟API调用延迟
      setTimeout(() => {
        this.listLoading = false
      }, 500)
    },
    // 获取职员列表
    async getStaffList() {
      const res = await selStaffListApi(this.listQuery)
      console.log(res)
      this.staffList = res.records || []
      this.total = res.total || 0
    },
    // 获取部门列表
    async getDepartmentList() {
      const res = await selDepartmentListApi(this.departmentListQuery)
      console.log(res)
      this.departmentList = res.records || []
      console.log(this.departmentList)
    },
    // 分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getStaffList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getStaffList()
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1
      this.getStaffList()
    },
    // 重置表单
    resetForm() {
      this.form = {
        loginName: '', // 登录名
        name: '', // 姓名
        mobile: '', // 手机号
        password: '', // 密码
        parent: '', // 部门
        sex: '' // 性别
      }
    },
    handleStatusChange(row) {
      this.$message({
        message: `${row.name} 状态已${row.enabled ? '启用' : '禁用'}`,
        type: 'success'
      })
    },
    // 新增
    handleAdd() {
      this.dialogFormVisible = true
      // this.form = {
      //   id: undefined,
      //   loginName: "",
      //   name: "",
      //   mobile: "",
      //   password: "",
      //   parent: "",
      //   sex: "",
      // };
    },
    // 编辑
    handleEdit(row) {
      this.dialogFormVisible = true
      this.form = {
        id: row.id,
        loginName: row.loginName,
        name: row.name,
        mobile: row.mobile,
        password: '', // 编辑时不显示密码
        parent: row.parent,
        sex: row.sex
      }
    },
    // 提交表单
    submitForm() {
      this.$refs.staffForm.validate(async(valid) => {
        if (valid) {
          try {
            const params = {
              loginName: this.form.loginName,
              name: this.form.name,
              mobile: this.form.mobile,
              password: this.form.password,
              parent: this.form.parent,
              sex: this.form.sex
            }

            if (!this.form.id) {
              // 新增职员
              const res = await addUserApi(params)
              console.log(res)
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '新增成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            } else {
              // 编辑职员
              const res = await updateUserByIdApi({
                ...params,
                id: this.form.id
              })
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '编辑成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            }

            this.dialogFormVisible = false
            this.getStaffList() // 刷新列表数据
          } catch (error) {
            console.error('操作失败:', error)
            this.$message({
              type: 'error',
              message: '操作失败: ' + (error.message || '未知错误')
            })
          }
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('此操作将永久删除该职员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await deleteUserByIdApi(row.id)
            if (res.code === 1) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getStaffList()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message({
              type: 'error',
              message: '删除失败: ' + (error.message || '未知错误')
            })
          }
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        })
    },
    handleImport() {
      this.$message({
        message: '导入职员',
        type: 'info'
      })
    },
    handleExport() {
      this.$message({
        message: '导出职员',
        type: 'info'
      })
    },
    handleRefresh() {
      this.getStaffList()
      this.$message({
        message: '刷新成功',
        type: 'success'
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 15px;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  text-align: center;
}
</style>
